<template>
<article>
    <el-button type="primary" style="float: right;margin-bottom: 10px;" size="mini" @click="showTagDialog('add')">添加新标签</el-button>
    <el-table ref="multipleTable" :data="tagList" tooltip-effect="dark" stripe border>
        <el-table-column type="index" width="55" align="center" header-align="center" :index="increment"></el-table-column>
        <el-table-column show-overflow-tooltip
                         v-if="!item.hidden"
                         v-for="(item, index) in headerOptions"
                         :key="index"
                         :label="item.label"
                         :prop="item.prop"
                         :header-align="item.headerAlign"
                         :align="item.align"
                         :min-width="item.minWidth || 100">
            <template slot-scope="scope">
              <div v-if="scope.column.property == 'createAt'||scope.column.property == 'updateAt'">{{scope.row[scope.column.property] | parseTime('{y}-{m}-{d} {h}:{i}')}}</div>
              <div v-else>{{scope.row[scope.column.property] || '无'}}</div>
            </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="150">
            <template slot-scope="scope">
            <el-button size="mini" @click="showTagDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="del(scope)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageindex"
      :page-sizes="size_scoped"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next"
      :total="tagTotal">
    </el-pagination>
    <el-dialog
      title="添加标签"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeTagDialog">
      <el-form :model="tagForm" :rules="rules" ref="tagForm" label-width="80px">
        <el-form-item label="标签名" prop="title">
          <el-input v-model="tagForm.title" placeholder="请输入标签名"></el-input>
        </el-form-item>
        <el-form-item label="标签值" prop="value">
          <el-input v-model="tagForm.value" placeholder="请输入标签值，仅接受英文"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini"  @click="cancelOperatedTag">取 消</el-button>
        <el-button size="mini" type="primary" @click="operatedTag">{{operatedType==='add'? '添 加' : '更新'}}</el-button>
      </span>
    </el-dialog>
</article>
</template>
<script>
    import { mapGetters } from 'vuex'
    export default {
      data() {
        var validateValue = (rule, value, callback) => {
          if (!value) {
            return callback(new Error('请输入分类值，仅接受英文'))
          }
          if (!(/^[a-zA-Z]+$/g).test(value)) {
            return callback(new Error('请输入英文'))
          }
          callback()
        }
        return {
          dialogVisible: false,
          loading: false,
          pageindex: 1,
          pagesize: 10,
          size_scoped: [10, 20, 30, 40],
          operatedType: 'add',
          headerOptions: [
            {
              label: 'id',
              prop: '_id',
              hidden: true,
              headerAlign: 'center',
              align: 'center',
              width: ''
            },
            {
              label: '标签名',
              prop: 'title',
              hidden: false,
              headerAlign: 'center',
              align: 'center',
              width: ''
            },
            {
              label: '标签值',
              prop: 'value',
              hidden: false,
              headerAlign: 'center',
              align: 'center',
              width: '',
              sort: true
            },
            {
              label: '创建日期',
              prop: 'createAt',
              hidden: false,
              headerAlign: 'center',
              align: 'center',
              width: ''
            },
            {
              label: '更新日期',
              prop: 'updateAt',
              hidden: false,
              headerAlign: 'center',
              align: 'center',
              width: '',
              sort: true
            }
          ],
          tagForm: {
            title: '',
            value: ''
          },
          rules: {
            title: [
              { required: true, message: '请输入标签名', trigger: 'blur' }
            ],
            value: [
              { validator: validateValue, trigger: 'blur' }
            ]
          }
        }
      },
      mounted() {
        this.getTagList()
      },
      methods: {
        increment(index) {
          return index + 1 + ((this.pageindex - 1) * this.pagesize)
        },
        async getTagList(index) {
          this.loading = true
          try {
            await this.$store.dispatch('GetTagList', {
              pageindex: index || this.pageindex,
              pagesize: this.pagesize
            })
            this.loading = false
          } catch (e) {
            this.loading = false
          }
        },
        del(scope) {
          this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(async() => {
            try {
              const message = await this.$store.dispatch('DelTag', scope.row._id)
              this.$message({
                type: 'success',
                message: message.msg
              })
              this.getTagList()
            } catch (e) {
              console.log('操作失败')
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        },
        operatedTag() {
          this.dialogVisible = true
          this.$refs['tagForm'].validate(async(valid) => {
            if (valid) {
              let fun = 'AddTag'
              const params = {
                title: this.tagForm.title || '',
                value: this.tagForm.value || ''
              }
              if (this.operatedType === 'add') {
                fun = 'AddTag'
              } else {
                fun = 'UpdateTag'
                params.id = this.tagForm._id
              }
              try {
                const message = await this.$store.dispatch(fun, params)
                this.$message({
                  type: 'success',
                  message: message.msg
                })
                this.getTagList()
                this.dialogVisible = false
              } catch (e) {
                console.log('操作失败')
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        },
        cancelOperatedTag() {
          this.$refs['tagForm'].resetFields()
          this.dialogVisible = false
        },
        showTagDialog(row) {
          this.operatedType = 'add'
          if (row !== 'add') {
            this.tagForm = JSON.parse(JSON.stringify(row))
            this.operatedType = 'edit'
          }
          this.dialogVisible = true
        },
        closeTagDialog() {
          this.tagForm = {}
        },
        handleCurrentChange(val) {
          this.pageindex = val
          this.getTagList()
        },
        handleSizeChange(val) {
          this.pagesize = val
          this.getTagList(1)
        }
      },
      computed: {
        ...mapGetters([
          'tagList',
          'tagTotal'
        ])
      }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
article {
  padding: 20px;
  .search {
    padding-bottom: 20px;
    background-color: rgba(255,255,255,.8);
    .el-input {
      width: 300px;
    }
  }
  .pagination {
    text-align: right;
    padding: 20px 0;
  }
  .tag {
    margin: 0 10px;
  }
}
</style>
